package service;

import dao.impl.*;
import org.apache.commons.beanutils.BeanUtils;
import pojo.*;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

public class ForegroundService {

    private MemberDaoImpl memberDao = new MemberDaoImpl();
    private TableDaoImpl tableDao = new TableDaoImpl();
    private OrderDaoImpl orderDao = new OrderDaoImpl();
    private TableInfoDaoImpl tableInfoDao = new TableInfoDaoImpl();
    private FoodDaoImpl foodDao = new FoodDaoImpl();
    private OrderFoodDaoImpl orderFoodDao = new OrderFoodDaoImpl();
    private OrderFoodBkDaoImpl orderFoodBkDao = new OrderFoodBkDaoImpl();
    private WorkerDaoImpl workerDao = new WorkerDaoImpl();
    private BillDaoImpl billDao = new BillDaoImpl();

    /**
     * 会员注册
     *
     * @param request
     * @param response
     */
    public void memberRegister(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Member member = new Member();
            BeanUtils.populate(member, parameterMap);
            if (memberDao.checkPhoneExist(member.getMemberPhone())) {
                Result.response(1002, "电话号码已存在！", response);
                return;
            }
            member.setMemberCreateTime(new Timestamp(System.currentTimeMillis()));
            member.setMemberUpdateTime(new Timestamp(System.currentTimeMillis()));
            member.setMemberPassword(MD5Util.MD55(member.getMemberPassword()));
            if (memberDao.memberRegister(member) > 0) {
                // 用于跳转至充值页面
                request.getSession().setAttribute("registerMember", memberDao.findMember(member));
                Result.response(200, "注册成功！", response);
                return;
            }
            Result.response(1001, "注册失败！", response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找会员
     *
     * @param request
     * @param response
     */
    public void findMember(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Member member = new Member();
            BeanUtils.populate(member, parameterMap);
            if (member.getMemberPhone() == null || member.getMemberPhone().isEmpty()) {
                Result.response(1002, "电话号码不能为空！", response);
                return;
            } else {
                Member daoMember = memberDao.findMember(member);
                if (daoMember.getMemberId() != null) {
                    Result.response(200, "查询成功!", response, daoMember);
                } else {
                    Result.response(1001, "该会员不存在！", response, daoMember);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 充值
     *
     * @param request
     * @param response
     */
    public void recharge(HttpServletRequest request, HttpServletResponse response) {
        String memberId = request.getParameter("memberId");
        String memberMoneyStr = request.getParameter("memberMoney");
        String rechargeMoneyStr = request.getParameter("rechargeMoney");
        if (!StringDataCheckUtil.check(memberMoneyStr) || !StringDataCheckUtil.check(rechargeMoneyStr)) {
            Result.response(1001, "请先查询手机号码！", response);
            return;
        }
        memberMoneyStr = memberMoneyStr.substring(0, memberMoneyStr.length() - 1);
        Double memberMoney = Double.valueOf(memberMoneyStr);
        Double rechargeMoney = Double.valueOf(rechargeMoneyStr);
        rechargeMoney += memberMoney;
        if (!StringDataCheckUtil.check(memberId)) {
            Result.response(1001, "数据有误！", response);
            return;
        }
        String workerId = request.getParameter("workerId");
        String workerPassword = request.getParameter("workerPassword");
        Worker workerById = workerDao.findWorkerById(workerId);
        if (workerById == null) {
            Result.response(1003, "数据有误！", response);
            return;
        }
        if (!workerById.getWorkerPassword().equals(MD5Util.MD55(workerPassword))) {
            Result.response(1005, "密码错误！", response);
            return;
        }
        if (memberDao.recharge(rechargeMoney, memberId) > 0) {
            // 增加账单记录信息
            Double billRest = billDao.findBillRest();
            Bill bill = new Bill();
            bill.setBillAction("会员充值 操作员：" + workerById.getWorkerName());
            bill.setBillMoney(Double.valueOf(rechargeMoneyStr));
            bill.setBillType(1);
            bill.setBillRest(billRest + Double.valueOf(rechargeMoneyStr));
            if (billDao.addBill(bill) <= 0) {
                Result.response(1004, "增加账单记录信息失败！", response);
                return;
            }
            Result.response(200, "充值成功！", response);
            return;
        } else {
            Result.response(1002, "充值失败！", response);
        }
    }

    /**
     * 查询所有餐桌
     *
     * @param request
     * @param response
     */
    public void tableList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Table> tableList = tableDao.tableList();
        //设置可预约时间
        Calendar now = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String month = String.valueOf(now.get(Calendar.MONTH) + 1);
        String date = String.valueOf(now.get(Calendar.DATE));
        String h = String.valueOf(now.get(Calendar.HOUR_OF_DAY));
        String m = String.valueOf(now.get(Calendar.MINUTE));
        String s = String.valueOf(now.get(Calendar.SECOND));
        if (Integer.valueOf(month) < 10) {
            month = "0" + date;
        }
        if (Integer.valueOf(date) < 10) {
            date = "0" + date;
        }
        if (Integer.valueOf(h) < 10) {
            h = "0" + h;
        }
        if (Integer.valueOf(m) < 10) {
            m = "0" + m;
        }
        if (Integer.valueOf(s) < 10) {
            s = "0" + s;
        }
        boolean CanBook = false;
        String nowt = now.get(Calendar.YEAR) + "-" + month + "-" + date + " " + h + ":" + m + ":" + s;
        String bkt = now.get(Calendar.YEAR) + "-" + month + "-" + date + " " + "11:00:00";
        try {
            Calendar nowtime = Calendar.getInstance();
            Calendar bktime = Calendar.getInstance();
            nowtime.setTime(sdf.parse(nowt));
            bktime.setTime(sdf.parse(bkt));
            CanBook = nowtime.getTime().after(bktime.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        request.setAttribute("tableList", tableList);
        request.setAttribute("CanBook", CanBook);
        request.getRequestDispatcher("/WEB-INF/pages/foreground/foregroundSystem/foregroundSystem.jsp").forward(request, response);
    }

    /**
     * 开台
     *
     * @param request
     * @param response
     */
    public void setUpTable(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String tableCapacity = request.getParameter("tableCapacity");
            TableInfo tableInfo = new TableInfo();
            BeanUtils.populate(tableInfo, parameterMap);
            // 判断人数
            if (Integer.valueOf(tableCapacity) < tableInfo.getTableInfoNum()) {
                Result.response(1004, "人数不能超过上限！", response);
                return;
            }
            // 设置餐桌状态
            if (tableDao.setUpTable(tableInfo.getTableId().toString()) <= 0) {
                LogUtil.addLog("设置餐桌状态失败",request, 0);
                Result.response(1001, "设置餐桌状态失败！", response);
                return;
            }
            // 生成订单
            Order order = new Order();
            order.setTableId(tableInfo.getTableId());
            if (orderDao.add(order) < 0) {
                LogUtil.addLog("生成订单失败",request, 0);
                Result.response(1002, "生成订单失败！", response);
                return;
            }
            // 生成餐桌信息(录入员工id 订单id 餐桌id 餐桌人数)
            tableInfo.setTableInfoOrderId(orderDao.findOrderIdByTableId(tableInfo.getTableId().toString()));
            if (tableInfoDao.add(tableInfo) < 0) {
                LogUtil.addLog("生成餐桌信息失败", request,0);
                Result.response(1003, "生成餐桌信息失败！", response);
                return;
            }

            Table table = tableDao.findEditTable(tableInfo.getTableId().toString());
            LogUtil.addLog("开台餐桌[" + table.getTableName() + "],人数[" + tableInfo.getTableInfoNum() + "]人", request);
            Result.response(200, "开台成功！", response);
            // 记录日志

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 预约餐桌
     *
     * @param request
     * @param response
     */
    public void bookTable(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String tableCapacity = request.getParameter("tableCapacity");
            String tomTime = request.getParameter("tomTime");
            String bookTime = request.getParameter("bookTime");
            String tableInfoBookTime = tomTime + " " + bookTime;
            TableInfo tableInfo = new TableInfo();
            BeanUtils.populate(tableInfo, parameterMap);
            tableInfo.setTableInfoBookTime(tableInfoBookTime);
            Table table = tableDao.findEditTable(tableInfo.getTableId().toString());
            // 判断人数
            if (Integer.valueOf(tableCapacity) < tableInfo.getTableInfoNum()) {
                Result.response(1004, "人数不能超过上限！", response);
                return;
            }
            // 加入餐桌信息
            if (tableInfoDao.addBookInfo(tableInfo) <= 0) {
                LogUtil.addLog("生成餐桌信息失败，餐桌id[" + tableInfo.getTableId() + "]", request,0);
                Result.response(1001, "生成餐桌信息失败！", response);
                return;
            }
            // 设置餐桌状态
            if (tableDao.bookTable(tableInfo.getTableId().toString()) <= 0) {
                LogUtil.addLog("设置餐桌状态失败，餐桌id[" + tableInfo.getTableId() + "]", request,0);
                Result.response(1002, "设置餐桌状态失败！", response);
                return;
            }
            LogUtil.addLog("预约了餐桌[" + table.getTableName() + "],人数[" + tableInfo.getTableInfoNum() + "]人", request);
            Result.response(200, "预约成功！", response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消餐桌预定
     *
     * @param request
     * @param response
     */
    public void cancelBookTable(HttpServletRequest request, HttpServletResponse response) {
        String tableId = request.getParameter("tableId");
        if (!StringDataCheckUtil.check(tableId)) {
            Result.response(1001, "参数不正确！", response);
            return;
        }
        if (tableDao.findEditTable(tableId) == null) {
            Result.response(1002, "餐桌不存在！", response);
            return;
        }
        if (tableDao.cancelBookTable(tableId) <= 0) {
            LogUtil.addLog("设置餐桌状态失败，餐桌id[" + tableId + "]", request,0);
            Result.response(1003, "改变餐桌状态失败！", response);
            return;
        }
        Table table = tableDao.findEditTable(tableId);
        LogUtil.addLog("取消餐桌[" + table.getTableName() + "]的预约", request);
        Result.response(200, "取消成功！", response);
    }

    /**
     * 获取所有可用的菜品类型
     *
     * @param request
     * @param response
     */
    public void findAllFoodTypeInUse(HttpServletRequest request, HttpServletResponse response) {
        List<FoodType> allFoodTypeInUse = foodDao.findAllFoodTypeInUse();
        if (allFoodTypeInUse == null) {
            Result.response(1001, "获取数据失败！", response);
            return;
        }
        Result.response(200, "获取成功！", response, allFoodTypeInUse);
    }

    /**
     * 获取所有菜品
     *
     * @param request
     * @param response
     */
    public void findAllFood(HttpServletRequest request, HttpServletResponse response) {
        Food food = new Food();
        food.setFoodIsDeleted(0);
        food.setPage(1);
        food.setLimit(999999);
        List<Food> foodListByParam = foodDao.findFoodListByParam(food);
        Integer count = foodDao.countFindFoodListByParam(food);
        if (foodListByParam == null) {
            Result.response(1001, "获取数据失败!", response);
            return;
        }
        Result.response(200, "获取成功！", count, response, foodListByParam);
    }

    /**
     * 根据菜品类型获取菜品
     *
     * @param request
     * @param response
     */
    public void findFoodListByParam(HttpServletRequest request, HttpServletResponse response) {
        String foodTypeCode1 = request.getParameter("foodTypeCode1");
        Food food = new Food();
        food.setFoodIsDeleted(0);
        if (Integer.valueOf(foodTypeCode1) != 0) {
            food.setFoodTypeCode(foodTypeCode1);
        }
        food.setPage(1);
        food.setLimit(999999);
        List<Food> foodListByParam = foodDao.findFoodListByParam(food);
        Integer count = foodDao.countFindFoodListByParam(food);
        if (foodListByParam == null) {
            Result.response(1001, "获取数据失败!", response);
            return;
        }
        Result.response(200, "获取成功！", count, response, foodListByParam);
    }

    /**
     * 订单添加菜品
     *
     * @param request
     * @param response
     */
    public void addOrderFood(HttpServletRequest request, HttpServletResponse response) {
        String foodCount = request.getParameter("foodCount");
        String foodId = request.getParameter("foodId");
        String tableId = request.getParameter("tableId");
        Integer orderId = orderDao.findOrderIdByTableId(tableId);
        Food food = foodDao.findFoodById(foodId);

        if (Integer.parseInt(foodCount) == 0) {
            // 新添加的菜品
            if (orderFoodDao.addNewOrderFood(orderId.toString(), food) > 0) {
                List<OrderFood> orderFoodByOrderId = orderFoodDao.findOrderFoodByOrderId(orderId.toString());
                Integer count = orderFoodByOrderId.size();
                Result.response(200, "订单添加新的菜品成功！", response, count);
                return;
            }
            Result.response(1001, "订单添加新菜品失败！", response);
            return;
        } else {
            // 已有的菜品
            Integer count = Integer.parseInt(foodCount) + 1;
            Double money = food.getFoodPrice() * count;
            if (orderFoodDao.addOrderFood(orderId.toString(), foodId, count.toString(), money.toString()) > 0) {
                List<OrderFood> orderFoodByOrderId = orderFoodDao.findOrderFoodByOrderId(orderId.toString());
                count = orderFoodByOrderId.size();
                Result.response(200, "订单添加菜品成功！", response, count);
                return;
            }
            Result.response(1001, "订单添加菜品失败！", response);
        }
    }

    /**
     * 获取餐桌的订单食品信息
     *
     * @param request
     * @param response
     */
    public void findOrderFoodByOrderID(HttpServletRequest request, HttpServletResponse response) {
        String orderId = request.getParameter("orderId");
        List<OrderFood> orderFoodList = orderFoodDao.findOrderFoodByOrderId(orderId);
        if (orderFoodList != null) {
            Result.response(200, "查询成功！", response, orderFoodList);
            return;
        }
        Result.response(1001, "查询失败！", response);
    }

    /**
     * 根据餐桌id获取订单id
     *
     * @param request
     * @param response
     */
    public void findOrderIdByTableID(HttpServletRequest request, HttpServletResponse response) {
        String tableId = request.getParameter("tableId");
        Integer orderIdByTableId = orderDao.findOrderIdByTableId(tableId);
        Result.response(200, "获取成功！", response, orderIdByTableId);
    }

    /**
     * 通过订单id查找订单
     *
     * @param request
     * @param response
     */
    public void findOrderByTableId(HttpServletRequest request, HttpServletResponse response) {
        String tableId = request.getParameter("tableId");
        Integer orderId = orderDao.findOrderIdByTableId(tableId);
        List<Order> detailOrderByTableId = orderDao.findDetailOrderByTableId(tableId, orderId.toString());
        if (detailOrderByTableId != null) {
            Result.response(0, "获取数据成功！", response, detailOrderByTableId);
            return;
        } else {
            Result.response(1001, "获取数据失败！", response);
        }
    }

    /**
     * 删除订单中的食品
     *
     * @param request
     * @param response
     */
    public void deleteOrderFood(HttpServletRequest request, HttpServletResponse response) {
        String[] ids = request.getParameterValues("ids[]");
        String orderId = request.getParameter("orderId");
        if (ids == null) {
            Result.response(1002, "参数不正确!", response);
        }
        Boolean res = false;
        // 遍历ids
        for (String id : ids) {
            res = orderFoodDao.delete(orderId, id) > 0 ? true : false;
        }
        if (res) {
            Result.response(200, "删除成功!", response);
            return;
        }
        Result.response(1001, "删除失败!", response);
    }

    /**
     * 减少一份订单中的食品
     *
     * @param request
     * @param response
     */
    public void subOrderFood(HttpServletRequest request, HttpServletResponse response) {
        String orderFoodId = request.getParameter("orderFoodId");
        String foodId = request.getParameter("foodId");
        String foodCount = request.getParameter("foodCount");
        if (!StringDataCheckUtil.check(orderFoodId) && !StringDataCheckUtil.check(foodId) && !StringDataCheckUtil.check(foodCount)) {
            Result.response(1001, "参数不正确！", response);
            return;
        }
        Integer integer = Integer.valueOf(foodCount);
        integer--;
        if (orderFoodDao.subOrderFood(orderFoodId, foodId, integer.toString()) > 0) {
            Result.response(200, "取消成功！", response);
            return;
        }
        Result.response(1002, "取消失败!", response);
    }

    /**
     * 提交订单
     *
     * @param request
     * @param response
     */
    public void submitOrder(HttpServletRequest request, HttpServletResponse response) {
        String orderId = request.getParameter("orderId");
        String orderMoney = request.getParameter("orderMoney");
        if (!StringDataCheckUtil.check(orderId) && !StringDataCheckUtil.check(orderMoney)) {
            Result.response(1001, "参数有误！", response);
            return;
        }
        // 修改订单的总额
        if (orderDao.updateOrderMoney(orderId, orderMoney) <= 0) {
            LogUtil.addLog("修改订单金额失败，订单id[" + orderId + "]",request, 0);
            Result.response(1002, "修改订单金额失败！", response);
            return;
        }
        // 添加订单食品备份信息
        // 根据订单id查找所有订单食品信息
        List<OrderFood> orderFoodByOrderId = orderFoodDao.findOrderFoodByOrderId(orderId);
        Boolean isSuccess = true;
        for (OrderFood orderFood : orderFoodByOrderId) {
            String foodId = orderFood.getFoodId().toString();
            String foodCount = orderFood.getFoodCount().toString();
            // 判断食品是否已经存在
            if (orderFoodBkDao.isBkExist(orderId, foodId) > 0) {
                // 存在则更新信息
                if (orderFoodBkDao.updateBk(orderId, foodId, foodCount) <= 0) {
                    isSuccess = false;
                }
            } else {
                if (orderFoodBkDao.addBk(orderId, foodId, foodCount) <= 0) {
                    isSuccess = false;
                }
            }
        }
        if (orderDao.setOrderPayTimeNULL(orderId) <= 0) {
            Result.response(1003, "设置订单支付时间有误！", response);
            return;
        }
        if (isSuccess) {
            Result.response(200, "提交订单成功！", response);
            return;
        }
        LogUtil.addLog("提交了订单，订单id为[" + orderId + "]", request);
        Result.response(1003, "提交订单失败！", response);
    }

    /**
     * 支付页面
     *
     * @param request
     * @param response
     */
    public void payPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tableId = request.getParameter("tableId");
        List<Table> tableList = tableDao.tableList();
        for (Table table : tableList) {
            if (table.getTableId().toString().equals(tableId)) {
                request.setAttribute("table", table);
                request.getRequestDispatcher("/WEB-INF/pages/foreground/foregroundSystem/pay.jsp").forward(request, response);
            }
        }
    }

    /**
     * 通过Id查找员工
     *
     * @param request
     * @param response
     */
    public void findWorkerById(HttpServletRequest request, HttpServletResponse response) {
        String workerId = request.getParameter("workerId");
        if (!StringDataCheckUtil.check(workerId)) {
            Result.response(1001, "参数有误！", response);
            return;
        }
        Worker workerById = workerDao.findWorkerById(workerId);
        if (workerById == null) {
            Result.response(1002, "查找失败！", response);
            return;
        }
        Result.response(200, "查找成功！", response, workerById);
    }

    /**
     * 非会员支付
     *
     * @param request
     * @param response
     */
    public void normalPay(HttpServletRequest request, HttpServletResponse response) {
        Connection connection = workerDao.getConnection();
        workerDao.setConnection(connection);
        orderDao.setConnection(connection);
        memberDao.setConnection(connection);
        tableDao.setConnection(connection);
        String orderId = request.getParameter("orderId");
        try {
            // 开启事务
            connection.setAutoCommit(false);
            String workerId = request.getParameter("workerId");
            String workerPassword = request.getParameter("workerPassword");
            // 验证数据
            if (!StringDataCheckUtil.check(workerId) && !StringDataCheckUtil.check(workerPassword)) {
                throw new Exception("参数有误!");
            }
            // 获取当前操作员的信息
            Worker workerById = workerDao.findWorkerById(workerId, connection);
            workerPassword = MD5Util.MD55(workerPassword);
            // 判断密码是否正确
            if (!workerPassword.equals(workerById.getWorkerPassword())) {
                throw new Exception("密码错误!");
            }
            String orderMoney = request.getParameter("orderMoney");
            if ("0".equals(orderMoney)) {
                // 将餐桌状态修改为空闲
                Order order = orderDao.findOrderById(orderId);
                Integer tableId = order.getTableId();
                if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                    throw new Exception("设置餐桌状态错误!");
                }
                //根据订单id删除餐桌信息
                if (tableInfoDao.deleteTableInfoByOrderId(orderId) <= 0) {
                    throw new Exception("删除餐桌信息错误!");
                }
                //根据订单id删除订单信息
                if (orderDao.deleteOrderByOrderId(orderId) <= 0) {
                    throw new Exception("删除订单信息错误!");
                }
                connection.commit();
                LogUtil.addLog("餐桌id：[" + tableId + "]取消开台成功", request);
                Result.response(200, "取消开台成功！欢迎重新正确选桌！", response);
            } else {
                if (orderMoney != null && !"".equals(orderMoney)) {
                    if (orderDao.updateOrderMoney(orderId, orderMoney, connection) <= 0) {
                        throw new Exception("修改订单金额失败!");
                    }
                    // 增加账单记录信息
                    Double billRest = billDao.findBillRest();
                    Bill bill = new Bill();
                    bill.setBillAction("非会员订单支付  操作员：" + workerById.getWorkerName());
                    bill.setBillMoney(Double.valueOf(orderMoney));
                    bill.setBillType(1);
                    bill.setBillRest(billRest + Double.valueOf(orderMoney));
                    if (billDao.addBill(bill, connection) <= 0) {
                        throw new Exception("增加账单记录信息失败!");
                    }
                }
                // 添加订单的操作人员名字
                if (orderDao.normalPay(orderId, workerById.getWorkerName(), connection) <= 0) {
                    throw new Exception("修改订单支付时间错误!");
                }
                // 将餐桌状态修改为空闲
                Order order = orderDao.findOrderById(orderId);
                Integer tableId = order.getTableId();
                if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                    throw new Exception("设置餐桌状态错误!");
                }
                connection.commit();
                LogUtil.addLog("非会员支付订单成功,订单id[" + orderId + "]", request);
                Result.response(200, "非会员支付成功！欢迎下次光顾！", response);
            }
        } catch (Exception e) {
            try {
                e.printStackTrace();
                connection.rollback();
                LogUtil.addLog(e.getMessage() + " 订单id[" + orderId + "]", request);
                Result.response(1010, "非会员支付失败！", response);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 会员的非余额支付
     *
     * @param request
     * @param response
     */
    public void memberNormalPay(HttpServletRequest request, HttpServletResponse response) {
        Connection connection = workerDao.getConnection();
        workerDao.setConnection(connection);
        orderDao.setConnection(connection);
        memberDao.setConnection(connection);
        tableDao.setConnection(connection);
        String orderId = request.getParameter("orderId");
        try {
            // 开启事务
            connection.setAutoCommit(false);
            Map<String, String[]> parameterMap = request.getParameterMap();
            Member member = new Member();
            BeanUtils.populate(member, parameterMap);
            member = memberDao.findMemberById(member.getMemberId().toString());
            if (member == null) {
                throw new Exception("查找会员失败");
            }
            // 判断密码是否正确
            String memberPassword = request.getParameter("memberPassword");
            memberPassword = MD5Util.MD55(memberPassword);
            if (!member.getMemberPassword().equals(memberPassword)) {
                throw new Exception("密码错误");
            }
            String payMoney = request.getParameter("payMoney");
            if ("0".equals(payMoney)) {
                // 将餐桌状态修改为空闲
                Order order = orderDao.findOrderById(orderId);
                Integer tableId = order.getTableId();
                if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                    throw new Exception("设置餐桌状态错误!");
                }
                //根据订单id删除餐桌信息
                if (tableInfoDao.deleteTableInfoByOrderId(orderId) <= 0) {
                    throw new Exception("删除餐桌信息错误!");
                }
                //根据订单id删除订单信息
                if (orderDao.deleteOrderByOrderId(orderId) <= 0) {
                    throw new Exception("删除订单信息错误!");
                }
                connection.commit();
                LogUtil.addLog("餐桌id：[" + tableId + "]取消开台成功", request);
                Result.response(200, "取消开台成功！欢迎重新正确选桌！", response);
            } else {
                if (orderDao.updateOrderMoney(orderId, payMoney, connection) <= 0) {
                    throw new Exception("修改订单金额失败");
                }
                if (orderDao.updateOrderIsMember(orderId, connection) <= 0) {
                    throw new Exception("修改订单支付类型失败！");
                }
                // 为会员增加积分
                String memberId = request.getParameter("memberId");
                if (memberDao.addMemberCount(memberId, payMoney, connection) <= 0) {
                    throw new Exception("增加会员积分失败！");
                }
                // 查询会员类型
                member = memberDao.findMemberById(memberId);
                MemberRole memberRole = memberDao.findRoleByCount(member.getMemberCount().toString());
                if (memberRole == null) {
                    throw new Exception("获取会员类型失败！");
                }
                // 更改会员类型
                if (memberDao.updateMemberRoleCode(memberId, memberRole.getMemberRoleCode().toString(), connection) <= 0) {
                    throw new Exception("更改会员类型失败！");
                }
                // 增加订单的会员支付人信息和收银员信息
                String workerId = request.getParameter("workerId");
                Worker workerById = workerDao.findWorkerById(workerId);
                if (orderDao.updateMemberInfo(member.getMemberName(), workerById.getWorkerName(), orderId, connection) <= 0) {
                    throw new Exception("更改订单会员支付信息失败！");
                }
                // 将餐桌状态修改为空闲
                Order order = orderDao.findOrderById(orderId);
                Integer tableId = order.getTableId();
                if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                    throw new Exception("设置餐桌状态错误！");
                }
                // 增加账单记录信息
                Double billRest = billDao.findBillRest();
                Bill bill = new Bill();
                bill.setBillAction(memberRole.getMemberRoleName() + ":" + member.getMemberName() + ",使用非余额支付订单  操作员：" + workerById.getWorkerName());
                bill.setBillMoney(Double.valueOf(payMoney));
                bill.setBillType(1);
                bill.setBillRest(billRest + Double.valueOf(payMoney));
                if (billDao.addBill(bill, connection) <= 0) {
                    throw new Exception("增加账单记录信息失败！");
                }
                connection.commit();
                LogUtil.addLog("会员非余额订单支付成功，订单id[" + orderId + "]", request);
                Result.response(200, "会员非余额支付成功！欢迎下次光顾！", response);
            }
        } catch (Exception e) {
            try {
                e.printStackTrace();
                connection.rollback();
                LogUtil.addLog(e.getMessage() + "订单id[" + orderId + "]", request,0);
                Result.response(1010, "会员非余额支付失败！", response);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 会员余额支付
     *
     * @param request
     * @param response
     */
    public void memberPay(HttpServletRequest request, HttpServletResponse response) {
        Connection connection = workerDao.getConnection();
        workerDao.setConnection(connection);
        orderDao.setConnection(connection);
        memberDao.setConnection(connection);
        tableDao.setConnection(connection);
        billDao.setConnection(connection);
        String orderId = request.getParameter("orderId");
        try {
            // 开启事务
            connection.setAutoCommit(false);
            Map<String, String[]> parameterMap = request.getParameterMap();
            Member member = new Member();
            BeanUtils.populate(member, parameterMap);
            member = memberDao.findMemberById(member.getMemberId().toString());
            if (member == null) {
                throw new Exception("查找会员失败");
            }
            // 判断密码是否正确
            String memberPassword = request.getParameter("memberPassword");
            memberPassword = MD5Util.MD55(memberPassword);
            if (!member.getMemberPassword().equals(memberPassword)) {
                throw new Exception("密码错误");
            }
            // 判断余额是否充足
            String payMoney = request.getParameter("payMoney");
            if ("0".equals(payMoney)) {
                // 将餐桌状态修改为空闲
                Order order = orderDao.findOrderById(orderId);
                Integer tableId = order.getTableId();
                if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                    throw new Exception("设置餐桌状态错误!");
                }
                //根据订单id删除餐桌信息
                if (tableInfoDao.deleteTableInfoByOrderId(orderId) <= 0) {
                    throw new Exception("删除餐桌信息错误!");
                }
                //根据订单id删除订单信息
                if (orderDao.deleteOrderByOrderId(orderId) <= 0) {
                    throw new Exception("删除订单信息错误!");
                }
                connection.commit();
                LogUtil.addLog("餐桌id：[" + tableId + "]取消开台成功", request);
                Result.response(200, "取消开台成功！欢迎重新正确选桌！", response);
            } else {
                if (Double.parseDouble(payMoney) >= member.getMemberMoney()) {
                    throw new Exception("余额不足");
                }

                //--------------------
                // 扣除会员余额
                if (!("1".equals(member.getMemberStatus()))) {
                    connection.rollback();
                    String a="";
                    if ("2".equals(member.getMemberStatus())){
                        a="该号码会员电话已挂失！";
                        LogUtil.addLog(a + "会员id[" + member.getMemberId().toString() + "]", request);
                        Result.response(1010, a+"支付失败", response);
                    }
                    if ("3".equals(member.getMemberStatus())){
                        a="该号码会员余额已冻结！";
                        LogUtil.addLog(a + "会员id[" + member.getMemberId().toString() + "]", request);
                        Result.response(1010, a+"支付失败", response);
                    }

                } else {
                    if (memberDao.subMoney(member.getMemberId().toString(), payMoney, connection) <= 0) {
                        throw new Exception("扣除余额失败");
                    }
                    String orderMoney = payMoney;
                    if (orderDao.updateOrderMoney(orderId, orderMoney, connection) <= 0) {
                        throw new Exception("修改订单金额失败");
                    }
                    if (orderDao.updateOrderIsMember(orderId, connection) <= 0) {
                        throw new Exception("修改订单支付类型失败！");
                    }
                    // 为会员增加积分
                    String memberId = request.getParameter("memberId");
                    if (memberDao.addMemberCount(memberId, orderMoney, connection) <= 0) {
                        throw new Exception("增加会员积分失败！");
                    }
                    // 查询会员类型
                    member = memberDao.findMemberById(memberId);
                    MemberRole memberRole = memberDao.findRoleByCount(member.getMemberCount().toString());
                    if (memberRole == null) {
                        throw new Exception("获取会员类型失败！");
                    }
                    // 更改会员类型
                    if (memberDao.updateMemberRoleCode(memberId, memberRole.getMemberRoleCode().toString(), connection) <= 0) {
                        throw new Exception("更改会员类型失败！");
                    }
                    // 增加订单的会员支付人信息和收银员信息
                    String workerId = request.getParameter("workerId");
                    Worker workerById = workerDao.findWorkerById(workerId);
                    if (orderDao.updateMemberInfo(member.getMemberName(), workerById.getWorkerName(), orderId, connection) <= 0) {
                        throw new Exception("更改订单会员支付信息失败！");
                    }
                    // 将餐桌状态修改为空闲
                    Order order = orderDao.findOrderById(orderId);
                    Integer tableId = order.getTableId();
                    if (tableDao.cancelBookTable(tableId.toString(), connection) <= 0) {
                        throw new Exception("设置餐桌状态错误！");
                    }
                    // 增加账单记录信息
                    Double billRest = billDao.findBillRest();
                    Bill bill = new Bill();
                    bill.setBillAction(memberRole.getMemberRoleName() + ":" + member.getMemberName() + ",使用余额支付订单  操作员：" + workerById.getWorkerName());
                    bill.setBillMoney(Double.valueOf(orderMoney));
                    bill.setBillType(1);
                    bill.setBillRest(billRest + Double.valueOf(orderMoney));
                    if (billDao.addBill(bill, connection) <= 0) {
                        throw new Exception("增加账单记录信息失败！");
                    }
                    connection.commit();
                    LogUtil.addLog("会员余额支付订单成功，订单id[" + orderId + "]", request);
                    Result.response(200, "会员余额支付成功！欢迎下次光顾！", response);
                }
            }


        } catch (Exception e) {
            try {
                e.printStackTrace();
                connection.rollback();
                LogUtil.addLog(e.getMessage() + "，订单id+[" + orderId + "]", request,0);
                Result.response(1010, "会员余额支付失败！", response, e.getMessage());
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

